/**
 * Copyright &copy; 2013-2015 山东易科德软件有限公司 All rights reserved.
 */
package cn.net.ecode.modules.sys.web;

import java.util.List;
import java.util.Map;

import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import cn.net.ecode.common.config.Global;
import cn.net.ecode.common.utils.IdGen;
import cn.net.ecode.common.utils.StringUtils;
import cn.net.ecode.common.web.BaseController;
import cn.net.ecode.modules.sys.entity.Dict;
import cn.net.ecode.modules.sys.service.DictService;

import com.google.common.collect.Lists;
import com.google.common.collect.Maps;

/**
 * 字典Controller
 * @author ThinkGem
 * @version 2014-8-19
 */
@Controller
@RequestMapping(value = "${adminPath}/sys/dict")
public class DictController extends BaseController {

	@Autowired
	private DictService dictService;
	
	/**
	 * 获取数据
	 * @param dictCode 获取数据编号
	 * @param isNewRecord 如果新记录，则不进行查询
	 * @return
	 */
	@ModelAttribute
	public Dict get(String dictCode, boolean isNewRecord) {
		return dictService.get(dictCode, isNewRecord);
	}
	
	/**
	 * 查询列表
	 */
	@RequiresPermissions("sys:dict:view")
	@RequestMapping(value = {"list", ""})
	public String list(Dict dict, Model model) {
		return "modules/sys/dictList";
	}
	
	/**
	 * 查询列表数据
	 */
	@RequiresPermissions("sys:dict:view")
	@ResponseBody
	@RequestMapping(value = "listData")
	public List<Dict> listData(Dict dict) {
		if (StringUtils.isBlank(dict.getParentCode())) {
			dict.setParentCode(Dict.ROOT_CODE);
		}
		List<Dict> list = null;
		if (StringUtils.isNotBlank(dict.getDictCode())){
			list = Lists.newArrayList(get(dict.getDictCode(), false));
		}else{
			if (!dict.getCurrentUser().isSuperAdmin()){
				dict.setIsSys(Global.NO);
			}
			list = dictService.findList(dict);
		}
		return list;
	}
	
	/**
	 * 查看编辑表单
	 */
	@RequiresPermissions("sys:dict:view")
	@RequestMapping(value = "form")
	public String form(Dict dict, Model model) {
		if (dict.getParent() != null && StringUtils.isNotBlank(dict.getParent().getDictCode())){
			dict.setParent(dictService.get(dict.getParent().getDictCode()));
			// 获取排序号，最末节点排序号+30
			if (StringUtils.isBlank(dict.getDictCode())){
				Dict dictChild = new Dict();
				dictChild.setParent(new Dict(dict.getParentCode()));
				List<Dict> list = dictService.findList(dict); 
				if (list.size() > 0){
					dict.setSorts(list.get(list.size()-1).getSorts());
					if (dict.getSorts() != null){
						dict.setSorts(dict.getSorts() + 30);
					}
				}
			}
			if (dict.getParent() != null){
				dict.setType(dict.getParent().getType());
				dict.setIsSys(dict.getParent().getIsSys());
			}
		}
		if (dict.getSorts() == null){
			dict.setSorts(30);
		}
		if (dict.getIsNewRecord()){
			dict.setIsNewRecord(true);
			dict.setDictCode(IdGen.nextId());
		}
		model.addAttribute("dict", dict);
		return "modules/sys/dictForm";
	}

	/**
	 * 保存数据
	 */
	@RequiresPermissions("sys:dict:edit")
	@ResponseBody
	@RequestMapping(value = "save")
	public String save(Dict dict) {
		if(Global.isDemoMode()){
			return renderResult(Global.FALSE, "演示模式，不允许操作！");
		}
		StringBuilder message = new StringBuilder();
		if (!beanValidator(message, dict)){
			return renderResult(Global.FALSE, message);
		}
		if (!dict.getCurrentUser().isSuperAdmin() && dict.getIsRoot()){
			return renderResult(Global.FALSE, "你没有权限，操作此数据！");
		}
		dictService.save(dict);
		return renderResult(Global.TRUE, "保存字典'" + dict.getName() + "'成功！");
	}
	
	/**
	 * 禁用字典
	 */
	@RequiresPermissions("sys:dict:edit")
	@ResponseBody
	@RequestMapping(value = "disable")
	public String disable(Dict dict, RedirectAttributes redirectAttributes) {
		if (Global.isDemoMode()) {
			return renderResult(Global.FALSE, "演示模式，不允许操作！");
		}
		dictService.disable(dict);
		return renderResult(Global.TRUE, "停用字典" + dict.getName() + "成功");
	}
	
	/**
	 * 启用字典
	 */
	@RequiresPermissions("sys:dict:edit")
	@ResponseBody
	@RequestMapping(value = "enable")
	public String enable(Dict dict, RedirectAttributes redirectAttributes) {
		if (Global.isDemoMode()) {
			return renderResult(Global.FALSE, "演示模式，不允许操作！");
		}
		dictService.enable(dict);
		return renderResult(Global.TRUE, "启用字典" + dict.getName() + "成功");
	}
	
	/**
	 * 删除数据
	 */
	@RequiresPermissions("sys:dict:edit")
	@ResponseBody
	@RequestMapping(value = "delete")
	public String delete(Dict dict) {
		if(Global.isDemoMode()){
			return renderResult(Global.FALSE, "演示模式，不允许操作！");
		}
		if (dict.getIsRoot() && !dict.getCurrentUser().isSuperAdmin()){
			return renderResult(Global.FALSE, "你没有权限，操作此数据！");
		}
		dictService.delete(dict);
		return renderResult(Global.TRUE, "删除字典成功！");
	}
	
	/**
	 * 获取树结构数据
	 * @param type
	 * @param extCode
	 * @param isShowCode 是否显示值（true or 1：显示在左侧；2：显示在右侧；false or null：不显示）
	 * @return
	 */
	@RequiresPermissions("user")
	@ResponseBody
	@RequestMapping(value = "treeData")
	public List<Map<String, Object>> treeData(String type, String extCode, String isShowCode) {
		List<Map<String, Object>> mapList = Lists.newArrayList();
		Dict dict = new Dict();
		dict.setType(type);
		List<Dict> list = dictService.findList(dict);
		for (int i=0; i<list.size(); i++){
			Dict e = list.get(i);
			if (StringUtils.isBlank(extCode) || (extCode!=null && !extCode.equals(e.getId()) && e.getParentCodes().indexOf(","+extCode+",")==-1)){
				Map<String, Object> map = Maps.newHashMap();
				map.put("id", e.getDictCode());
				map.put("pId", e.getParentCode());
				map.put("pIds", e.getParentCodes());
				if ("true".equals(isShowCode) || "1".equals(isShowCode)){
					map.put("name", "(" + e.getValue() + ")" + StringUtils.replace(e.getName(), " ", ""));
				}else if ("2".equals(isShowCode)){
					map.put("name", StringUtils.replace(e.getName(), " ", "") + "(" + e.getValue() + ")");
				}else{
					map.put("name", StringUtils.replace(e.getName(), " ", ""));
				}
				map.put("value", e.getValue());
				mapList.add(map);
			}
		}
		return mapList;
	}

	@RequiresPermissions("sys:dict:edit")
	@ResponseBody
	@RequestMapping(value = "dataFix")
	public String dataFix(){
		dictService.updateFixParentCodes();
		return renderResult(Global.TRUE, "数据修复成功");
	}
}
